package ar.com.ford.it.fullEconomics.persistence.dao.query;

import java.sql.Timestamp;
import oracle.toplink.expressions.Expression;
import oracle.toplink.expressions.ExpressionBuilder;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesg01Plant;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesp01Part;
import com.ford.it.persistence.impl.toplink.CustomExpressionFactory;

public class PartsFindQuery implements CustomExpressionFactory {

    public Expression createExpression(ExpressionBuilder builder,
                                       Object[] parameters) {
        Expression exp = null;
        Teesp01Part part = (Teesp01Part) parameters[0];
        Timestamp dateInMax = (Timestamp) parameters[1];
        Timestamp dateOutMax = (Timestamp) parameters[2];
        
        Timestamp dateInMin = part.getEesp01PartInDateY();
        Timestamp dateOutMin = part.getEesp01PartOutDateY();
        String prefix = part.getEesp01PartPrefixCodeC();
        String base = part.getEesp01PartBaseCodeC();
        String suffix = part.getEesp01PartSuffixCodeC();
        String partClass = part.getEesp01PartClassCodeC();
        Teesg01Plant plant = part.getEesp01PlantCodeC();

        exp = builder.get("eesp01PlantCodeC").equal(plant);
        if(dateInMin != null)
            exp = exp.and(builder.get("eesp01PartInDateY").between(dateInMin, dateInMax));
        if(dateOutMin != null)
            exp = exp.and(builder.get("eesp01PartOutDateY").between(dateOutMin, dateOutMax));
        if(!partClass.equalsIgnoreCase("-1"))
            exp = exp.and(builder.get("eesp01PartClassCodeC").equal(partClass));
        if (prefix != null) {
            prefix += "%";
            exp = exp.and(builder.get("eesp01PartPrefixCodeC").toChar().like(prefix));
        }
        if (base != null) {
            base += "%";
            exp = exp.and(builder.get("eesp01PartBaseCodeC").toChar().like(base));
        }
        if (suffix != null) {
            suffix += "%";
            exp = exp.and(builder.get("eesp01PartSuffixCodeC").toChar().like(suffix));
        }
        
        return exp;
    }
}
